﻿namespace HuwmanCode.Diagnostics.Logging

open System
open System.Globalization
open System.Transactions
open System.Runtime.Serialization
open System.Reflection
open HuwmanCode
open HuwmanCode.Transactions
open HuwmanCode.Diagnostics

/// <summary>
/// The Windows event writer
/// </summary>
type public WindowsEventWriter() = 
    interface ILogWriter with
        /// <summary>
        /// The Windows event writer
        /// </summary>
        member this.Write message =
            try 
                let sourceExists = System.Diagnostics.EventLog.SourceExists(message.ExecutableName)
                if not sourceExists then System.Diagnostics.EventLog.CreateEventSource(message.ExecutableName, "Application")
            with _ -> ()

            let eventType =
                match message.Level with
                | TraceLevel.Debug -> Some System.Diagnostics.EventLogEntryType.Information
                | TraceLevel.Info  -> Some System.Diagnostics.EventLogEntryType.Information
                | TraceLevel.Warn  -> Some System.Diagnostics.EventLogEntryType.Warning
                | TraceLevel.Error -> Some System.Diagnostics.EventLogEntryType.Error
                | TraceLevel.Fatal -> Some System.Diagnostics.EventLogEntryType.Error
                | _ -> None

            match eventType with
            | None -> ()
            | Some eventType -> System.Diagnostics.EventLog.WriteEntry(message.ExecutableName, message.ToString(), eventType)

    interface IDisposable with
        member this.Dispose () =
            ()